/**
 * @description axios 配置文件
 * @author LI
 * @date 2020-11-16 19:36
 */

import axios, { AxiosResponse } from 'axios'
import { checkStatus } from '@/utils/axios/checkStatus'
import { AxiosTransform } from '@/utils/axios/AxiosTransform'
import { isDev } from '@/utils/env'
import { ContentTypeEnum, CreateAxiosOptions, Result } from '@/utils/axios/types'
import { VAxios } from '@/utils/axios/Axios'
import { cookies } from '@/utils/cookies'

const transform: AxiosTransform = {
  /**
   * @description: 处理请求数据
   */
  transformRequestData: (response: AxiosResponse<Result>) => {
    return response.data
  },

  /**
   * @description: 请求之前处理config
   */
  beforeRequestHook: (config) => {
    if (isDev()) {
      if (config.method === 'get') {
        // 给 get 请求加上时间戳参数，避免从缓存中拿数据。
        const now = new Date().getTime()
        const url = config.url || ''
        url.indexOf('?') === -1
          ? (config.url = url + '?_=' + now)
          : (config.url = url + '&_=' + now)
      }
    }
    return config
  },

  /**
   * @description: 请求拦截器处理
   */
  requestInterceptors: (config) => {
    // config.headers['token'] = cookies.get('token')
    config.headers['Authorization'] = 'Bearer ' + cookies.get('token')
    return config
  },

  /**
   * @description: 响应错误处理
   */
  responseInterceptorsCatch: (error: any) => {
    checkStatus(error.response.status)
    return error
  }
}

function createAxios(opt?: Partial<CreateAxiosOptions>) {
  return new VAxios({
    timeout: 10 * 1000,
    baseURL: process.env.VUE_APP_API,
    headers: { 'Content-Type': ContentTypeEnum.JSON },
    // 数据处理方式
    transform
  })
}

export const service = createAxios()
